package com.example.elderlycare.service.Impl;

import com.example.elderlycare.config.ZhenziSmsConfig;
import com.example.elderlycare.dao.entity.SmsLog;
import com.example.elderlycare.dao.mapper.SmsLogMapper;
import com.example.elderlycare.exception.AuthCodeExpiredException;
import com.example.elderlycare.exception.AuthCodeNotMatchException;
import com.example.elderlycare.exception.NoBalanceException;
import com.example.elderlycare.service.SmsService;
import com.example.elderlycare.service.entity.SmsResponseBody;
import com.example.elderlycare.utils.ZhenziSms;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.UUID;

@Service
public class SmsServiceImpl implements SmsService {
    @Resource
    ZhenziSms zhenziSms;

    @Resource
    SmsLogMapper smsLogMapper;

    @Resource
    ZhenziSmsConfig zhenziSmsConfig;

    @Override
    public SmsResponseBody sendAuthCode(String phoneNumber, String authCode) throws NoBalanceException {
        /* 余额不足，抛出异常 */
        if (zhenziSms.checkBalance() < 1) {
            throw new NoBalanceException();
        }
        boolean flag = zhenziSms.sendMessage(phoneNumber, authCode);
        if (flag) {
            UUID uuid = UUID.randomUUID();
            smsLogMapper.insert(new SmsLog(uuid.toString(), new Date(), phoneNumber, authCode));
            return new SmsResponseBody(uuid.toString());
        }
        return null;
    }


    @Override
    public boolean verifyAuthCode(String uuid, String authCode)
            throws AuthCodeExpiredException, AuthCodeNotMatchException {
        SmsLog smsLog = smsLogMapper.selectById(uuid);
        String code = smsLog.getCode();
        Date createdAt = smsLog.getCreatedAt();
        if (System.currentTimeMillis() - createdAt.getTime() > zhenziSmsConfig.getTimeOut() * 1000 * 60) {
            throw new AuthCodeExpiredException();
        }

        if (!code.equals(authCode)) {
            throw new AuthCodeNotMatchException();
        }

        return true;
    }

    @Override
    public SmsLog getSmsLogByUuid(String uuid) {
        return smsLogMapper.selectById(uuid);
    }
}
